<template>
  <el-dialog :title="title" :visible.sync="open" width="70%">
    <div class="remark-content">
      <p>1、费用单修改后的计费结束时间不能大于原单的计费结束时间</p>
      <p>2、拆费之后产生的费用单应收金额是可以修改的</p>
      <p>3、拆费产生的单子应收金额累加必须等于原单的应收金额</p>
    </div>
    <el-table v-loading="loading" :data="demoList" border size="mini">
      <el-table-column label="房屋名称" align="left" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.roomName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="left" prop="ownerName" width="100" />
      <el-table-column label="收费标准" align="left" prop="normNames" width="100" show-overflow-tooltip/>
      <el-table-column label="费用期间" align="center" prop="fiscalPeriod" width="100" />
      <el-table-column label="计费开始日期" align="center" prop="newBeginTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.newBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计费结束日期" align="center" prop="newFinishTime" width="190">
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.newFinishTime"
            type="date"
            placeholder="计费结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="{disabledDate:(time)=>{return disabledDate(time,scope.row)}}"
            @change="(v)=>changeFinishTime(v,scope.row,scope.$index)"
          >
          </el-date-picker>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单价" align="center" prop="prices" width="60"/> -->
      <!--<el-table-column label="金额" align="center" prop="moneys"  width="100"/>-->
      <el-table-column label="应收金额" align="center" prop="receivableMoney" width="120">
        <template slot-scope="scope">
          <el-input style="width: 90px;" v-model="scope.row.receivableMoney" placeholder="应收金额"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="!scope.row.costId"
            @click="delDemoLition(scope.row,scope.$index)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
  import {
    listMixin
  } from "@/utils/mixins/listMixin";

  import { executeDemolitionFee } from "@/api/payfee/ruleCost";

  export default {
    name: "recordTable",
    mixins: [listMixin],
    dicts: ['charge_status'],
    data() {
      return {
        title:'拆费',
        open:false,
        demoList: [],
      }
    },
    methods: {
      show(option){
        this.reset()
        this.open = true
        let demoList = JSON.parse(option.ruleCostList)
        demoList.forEach(row=>{
          row['newBeginTime'] = row.beginTime
          row['newFinishTime'] = row.finishTime
          row['newReceivableMoney'] = row.receivableMoney
          row['groupId'] = row.costId //使用原始ID当作单子的分组ID
        })
        this.demoList = demoList

      },
      selectDate(row) {

      },
      cancel() {
        this.open = false;
        this.reset();
      },
      reset(){
        this.demoList = []
      },
      disabledDate(time,row){
        let beginTime = new Date(row.beginTime);
        let finishTime = new Date(row.finishTime);
        return time.getTime() <  beginTime.getTime() || time.getTime()> finishTime.getTime() ;
      },
      changeFinishTime(v,row,index){
        let demoList = [...this.demoList] //复制拆费列表
        let newRow = this.createNewFeeForm(v,row) //新创建的费用单
        demoList[index].newFinishTime = this.$utils.toDateString(v,'yyyy-MM-dd')
        demoList[index].finishTime = this.$utils.toDateString(v,'yyyy-MM-dd')
        demoList.splice(index+1,0,newRow) //插入到原单的后面
        this.computeFee(row,demoList)
        this.demoList = demoList
      },
      //重新计算费用
      computeFee(row,demoList){
        //刚开始要先计算出每天的费用
        let toolDay = this.getTotalDay(row,demoList)
        let dayMone = 0 // 每天的费用
        if(row.moneys > 0){
          dayMone =this.$utils.divide(row.moneys, toolDay)  //总费用除于总天数=每天的费用
        }
        let groupDemoList = demoList.filter(x=> x.groupId ===  row.groupId )
        //如果就一条的话
        if(groupDemoList.length === 1){
          groupDemoList[0].newReceivableMoney =  groupDemoList[0].moneys
          groupDemoList[0].receivableMoney =  groupDemoList[0].moneys
        }else{
          //拆费之后总的费用
          let maxMoneys = 0
          for(let i in groupDemoList){
            let item = groupDemoList[i]
            //是最后一条费用单的话
            if(i == groupDemoList.length){
              let moneys = this.$utils.toFixed(this.$utils.subtract(row.moneys,maxMoneys),2)
              item.newReceivableMoney = this.$utils.subtract(row.moneys,maxMoneys)
              item.receivableMoney = this.$utils.subtract(row.moneys,maxMoneys)
            }else{
              //相差的天数
              let betweenDay = this.$utils.between(Date.parse(item.beginTime),Date.parse(item.finishTime))
              //相差的天数乘于每天的费用=应收金额
              let moneys = this.$utils.toFixed(this.$utils.multiply(betweenDay,dayMone),2)
              item.newReceivableMoney = moneys
              item.receivableMoney = moneys
              maxMoneys = this.$utils.add(maxMoneys, moneys)
            }
          }
        }
      },
      //创建新的费用单
      createNewFeeForm(v,row){
        //记录原始费用单的开始时间和结束时间
        let finishTime = row.finishTime
        //新单子的开始时间
        let newBeginTime = this.$utils.toDateString(this.$utils.getWhatDay(v,1),'yyyy-MM-dd')
        let newFinishTime = this.$utils.toDateString(finishTime,'yyyy-MM-dd')
        return {...row,...{
            beginTime: newBeginTime,  //新单子的开始时间是选的时间+1天
            finishTime: newFinishTime, //结束时间是原始单子的结束时间
            newBeginTime: newBeginTime,
            newFinishTime: newFinishTime,
            newReceivableMoney:0,
            receivableMoney:0,
            costId: null
        }}
      },
      //获取拆单的总天数
      getTotalDay(row,demoList){
        let groupDemoList = demoList.filter(x=> x.groupId ===  row.groupId )
        if(groupDemoList.length > 0){
          let startDate = Date.parse(groupDemoList[0].beginTime)
          let endDate = Date.parse(groupDemoList[groupDemoList.length -1].finishTime)
          return this.$utils.between(startDate,endDate)
        }
      },
      //删除拆分出来的单子
      delDemoLition(row,index){
        let demoList = [...this.demoList] //复制拆费列表
        demoList[index-1].finishTime = row.finishTime
        demoList[index-1].newFinishTime = row.finishTime
        demoList.splice(index,1)
        this.computeFee(row,demoList)
        this.demoList = demoList
      },
      saveData(){
        let demoList = this.demoList.filter(x=> !x.costId)
        if(demoList.length > 0){
          let demolitionVos = []
          this.demoList.forEach(row=>{
            demolitionVos.push({
              costId: row.costId,
              beginTime: row.beginTime,
              finishTime: row.finishTime,
              receivableMoney: row.newReceivableMoney,
              groupId: row.groupId
            })
          })
          executeDemolitionFee({demolitionVos: demolitionVos}).then(res=>{
            this.msgSuccess("拆费成功！");
            this.$emit("ok")
            this.cancel()
          })
        }else{
          this.msgWarning("没有需要拆费的费用单");
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog__body{
    padding: 5px 10px;
  }
  .remark-content{
    font-size: 12px;
    color: red;
  }
</style>
